<template>
  <div class="app-container" v-loading="isLoading">
    <div class="w-map" id="security-map"></div>
    <div class="w-right">
      <div class="w-title">
        <div>
          <span v-if="isDrawGon">超高建筑区域</span>
          <span v-else>覆盖区域</span>
        </div>
        <div></div>
      </div>
      <div class="w-right-box" v-if="isDrawGon">
        <h3 class="w-box-title">测量结果</h3>
        <div class="w-cell">
          <span>面积:</span>
          <p>{{ activeGonObj.area }}㎡</p>
        </div>
        <div class="w-cell">
          <span>建筑高度</span>
          <input
            v-model="activeGonObj.height"
            @input="heightInputUploadactiveGonObj"
            type="text"
          />
        </div>

        <div class="w-delete-btn" @click="deleteConstructArea">删除</div>
      </div>

      <div class="w-right-box" v-else>
        <div class="w-cell">
          <span>区域划分</span>
          <div class="w-select">
            <el-select
              v-model="sector.areaNum"
              @change="uploadSector"
              placeholder="请选择"
            >
              <el-option label="1" :value="1"></el-option>
              <el-option label="2" :value="2"></el-option>
              <el-option label="4" :value="4"></el-option>
              <el-option label="8" :value="8"></el-option>
            </el-select>
          </div>
        </div>
        <div class="w-cell">
          <span>倾斜角</span>
          <input
            @input="tiltInputUploadSector"
            v-model="sector.tilt"
            type="text"
          />
        </div>
        <div class="w-cell">
          <span>默认高度</span>
          <input v-model="sector.height" type="text" />
        </div>
        <h3 class="w-box-title">区域设置（m）</h3>
        <div class="w-area">
          <div
            class="w-cell1"
            v-for="(item, index) in sector.areaList"
            :key="index"
            v-show="index + 1 <= sector.areaNum"
          >
            <span>{{ item.areaName }}</span>
            <input
              @input="inputUploadSector(index)"
              v-model="item.radius"
              type="text"
            />
          </div>
        </div>
      </div>

      <div class="w-btn">
        <div @click="rightSave" style="background: rgba(122, 144, 253, 0.6)">
          保存
        </div>
        <div @click="rightCancel">取消</div>
      </div>
    </div>
    <div class="w-right-tool">
      <el-tooltip
        class="item"
        effect="dark"
        content="超高建筑"
        placement="left"
      >
        <img @click="openDrawGon" src="@/assets/images/tall.png" alt="" />
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="位置搜索"
        placement="left"
      >
        <img
          @click="ShowAddressSearch"
          src="@/assets/images/search.png"
          alt=""
        />
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="地图类型切换"
        placement="left"
      >
        <img @click="switchLayer" src="@/assets/images/qiehaun.png" alt="" />
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="地图放大"
        placement="left"
      >
        <img @click="addZoom" src="@/assets/images/fangda.png" alt="" />
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="地图缩小"
        placement="left"
      >
        <img @click="reduceZoom" src="@/assets/images/suoxiao.png" alt="" />
      </el-tooltip>
    </div>
    <div class="w-right-search" v-if="isShowAddressSearch">
      <el-select
        style="width: 100%; height: 40px"
        v-model="addressSearch"
        filterable
        remote
        reserve-keyword
        placeholder="请输入关键词"
        :remote-method="remoteMethod"
        @change="addressSelect"
        :loading="addressSearchLoading"
      >
        <el-option
          v-for="item in addressOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { amapKey, amapSecretkey } from "@/utils/use-g-map";
import { detAirport, putAirport } from "@/api/cruise/airdrome";
import { uploadPlanImg } from "@/api/command/plan";
import { createUniqueString } from "@/utils/index";
import html2canvas from "html2canvas";
export default {
  data() {
    return {
      map: null, // 地图实例
      zoom: 10,
      placeSearch: null, // 存放地图搜索对象
      isShowAddressSearch: false, //是否显示搜索
      addressSearch: "", // 地址选择
      addressOptions: [], // 地址搜索列表
      addressSearchLoading: false, // 地址搜索加载
      addressMarker: null, // 搜索到地址的点位对象
      isaddLayer: false,
      satellite: null, //卫星图层
      detData: {},
      sector: {
        areaNum: 8, // 区域数量
        tilt: 10, // 倾斜角
        height: 150, // 默认高度
        areaList: [
          { areaName: "A区", radius: 3000 },
          { areaName: "B区", radius: 4000 },
          { areaName: "C区", radius: 5000 },
          { areaName: "D区", radius: 2000 },
          { areaName: "E区", radius: 1000 },
          { areaName: "F区", radius: 3500 },
          { areaName: "G区", radius: 3000 },
          { areaName: "H区", radius: 4000 },
        ],
        constructAreaList: [], // 超高建筑点位
      },
      customLayer: null, // 安全区域图层
      fanCanvas: null, // 安全区域canvas
      isDrawGon: false, // 是否开启超高建筑绘画
      isAddMarker: false,
      faceMarker: [], //超高建筑实例
      activeGonObj: {
        area: 0,
        color: "#627bf2",
        lat: 0,
        lng: 0,
        id: "",
        pathList: [],
        height: 500,
      },
      isScreenshot: false, //图片是否上传完成
      timer: null,
      isLoading: false,
    };
  },
  methods: {
    // 删除超高建筑
    deleteConstructArea() {
      console.log(this.activeGonObj);
      let index = this.sector.constructAreaList.findIndex(
        (item) => item.id == this.activeGonObj.id
      );
      if (index != -1) {
        this.sector.constructAreaList.splice(index, 1);
        this.loadAllGon();
        this.isDrawGon = false;
        this.isAddMarker = false;
      } else {
        this.rightCancel();
      }
    },
    // 右侧按钮保存
    rightSave() {
      if (this.isDrawGon) {
        this.isDrawGon = false;
        let index = this.sector.constructAreaList.findIndex(
          (item) => item.id == this.activeGonObj.id
        );
        if (index == -1) {
          this.sector.constructAreaList.push(this.activeGonObj);
        } else {
          this.sector.constructAreaList[index] = this.activeGonObj;
        }
        this.isAddMarker = false;
        this.loadAllGon();
      } else {
        this.isLoading = true;
        // console.log("this.sector",this.sector)
        this.detData.sector = JSON.stringify(this.sector);
        this.getMapImg();
        this.timer = setInterval(() => {
          if (this.isScreenshot) {
            putAirport(this.detData).then((res) => {
              // console.log("机场保存",res)
              clearInterval(this.timer);
              this.$modal.msgSuccess("保存成功");
              this.timer = null;
              this.isLoading = false;
              this.$router.go(-1);
            });
          }
        }, 1000);
      }
    },
    // 右侧按钮取消
    rightCancel() {
      if (this.isDrawGon) {
        this.isDrawGon = false;
        this.isAddMarker = false;
        this.loadAllGon();
        console.log("this.faceMarker", this.faceMarker);
      } else {
        this.$router.go(-1);
      }
    },
    // 截图高德地图
    getMapImg() {
      let _this = this;
      window.pageYOffset = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      html2canvas(document.getElementById("security-map"), {
        backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        useCORS: true, //支持图片跨域
        scale: 0.5, //设置放大的倍数
      }).then((canvas) => {
        // console.log("canvas",canvas)
        canvas.toBlob((blob) => {
          let fd = new FormData();
          fd.append("file", blob);
          uploadPlanImg(fd, _this.uploadProgress).then((res) => {
            // console.log("res",res)
            _this.detData.airportPicture = res.url;
            _this.isScreenshot = true;
          });
        });
      });
    },
    uploadProgress(e) {
      console.log("进度", e);
    },
    // 加载所有超高建筑
    loadAllGon() {
      this.faceMarker.forEach((item) => {
        item.marker.forEach((item) => item.remove());
        item.marker = [];
        item.canvas.remove();
        item.gon._container.remove();
        item.text.remove();
        // item.canvas = null
        // item.gon = null
        item.text = null;
      });
      this.faceMarker = [];
      this.sector.constructAreaList.forEach((item) => {
        this.drawGon(item, false);
      });
    },

    // 开启超高建筑绘画
    openDrawGon() {
      this.isDrawGon = true;
    },
    // 绘画超高建筑区域
    drawGon(activeGonObj, isDraggable) {
      let _this = this;
      let index = this.faceMarker.findIndex(
        (item) => item.id == activeGonObj.id
      );
      if (index != -1) {
        let path = activeGonObj.pathList.map((item) => {
          return [item.lng, item.lat];
        });
        _this.drawPolygon(_this.map, path, this.faceMarker[index]);
        let center = this.getPolygonCenter(path);
        this.faceMarker[index].text.remove();
        // let position = new AMap.LngLat(center.lng,center.lat)
        // this.faceMarker[index].text.setPosition(position)
        // this.faceMarker[index].text.setOffset(new AMap.Pixel(0, 0))
        activeGonObj.lng = center.lng;
        activeGonObj.lat = center.lat;
        // 获取区域面积
        activeGonObj.area = Math.round(AMap.GeometryUtil.ringArea(path));
        // this.faceMarker[index].text.setText(activeGonObj.area + '㎡')
        this.faceMarker[index].text = new AMap.Text({
          extData: JSON.stringify(activeGonObj),
          text: activeGonObj.area + "㎡",
          anchor: "center", // 设置文本标记锚点
          draggable: false,
          cursor: "pointer",
          style: {
            padding: "5px",
            "border-radius": "5px",
            "background-color": "rgb(66, 61, 66)",
            width: "auto",
            "border-width": 0,
            "text-align": "center",
            "font-size": "14px",
            color: "#fff",
          },
          position: [activeGonObj.lng, activeGonObj.lat],
          offset: new AMap.Pixel(0, 0),
          zIndex: 10000,
        });
        this.map.add(this.faceMarker[index].text);
        this.faceMarker[index].marker.forEach((item) => {
          item.remove();
        });
        this.faceMarker[index].marker = [];
        if (isDraggable) {
          activeGonObj.pathList.forEach((item) => {
            var icon = new AMap.Icon({
              size: new AMap.Size(12, 12),
              image: require("@/assets/images/mapicon/road.png"),
              imageSize: new AMap.Size(12, 12),
              imageOffset: new AMap.Pixel(0, 0),
            });
            let marker = new AMap.Marker({
              extData: JSON.stringify(item),
              position: [item.lng, item.lat],
              icon: icon,
              offset: new AMap.Pixel(-6, -6),
              draggable: isDraggable,
              zIndex: 9999,
            });
            _this.map.add(marker);
            marker.on("dragging", _this.markerDragging);
            _this.faceMarker[index].marker.push(marker);
          });
        }
      } else {
        let obj = {
          gon: null,
          canvas: null,
          marker: [],
          id: activeGonObj.id,
          text: null,
        };
        let path = [];
        activeGonObj.pathList.forEach((item) => {
          if (isDraggable) {
            var icon = new AMap.Icon({
              size: new AMap.Size(12, 12),
              image: require("@/assets/images/mapicon/road.png"),
              imageSize: new AMap.Size(12, 12),
              imageOffset: new AMap.Pixel(0, 0),
            });
            let marker = new AMap.Marker({
              extData: JSON.stringify(item),
              position: [item.lng, item.lat],
              icon: icon,
              offset: new AMap.Pixel(-6, -6),
              draggable: isDraggable,
              zIndex: 9999,
            });
            marker.on("dragging", _this.markerDragging);
            _this.map.add(marker);
            obj.marker.push(marker);
          }
          path.push([item.lng, item.lat]);
        });
        let offset = null;
        if (isDraggable) {
          offset = new AMap.Pixel(0, -40);
        } else {
          offset = new AMap.Pixel(0, 0);
        }
        var text = new AMap.Text({
          extData: JSON.stringify(activeGonObj),
          text: activeGonObj.area + "㎡",
          anchor: "center", // 设置文本标记锚点
          draggable: false,
          cursor: "pointer",
          style: {
            padding: "5px",
            "border-radius": "5px",
            "background-color": "rgb(66, 61, 66)",
            width: "auto",
            "border-width": 0,
            "text-align": "center",
            "font-size": "14px",
            color: "#fff",
          },
          position: [activeGonObj.lng, activeGonObj.lat],
          offset: offset,
          zIndex: 10000,
        });
        text.on("click", _this.textClick);
        _this.map.add(text);
        obj.text = text;
        _this.drawPolygon(_this.map, path, obj);
        this.faceMarker.push(obj);
      }
    },
    // 使用canvas画面
    drawPolygon(map, path, obj) {
      // console.log("使用canvas画面",obj)
      if (!obj.canvas) {
        obj.canvas = document.createElement("canvas");
      }
      let onRender = function () {
        let size = map.getSize();
        obj.canvas.style.width = size.width + "px";
        obj.canvas.style.height = size.height + "px";
        obj.canvas.width = size.width;
        obj.canvas.height = size.height;
        let ctx = obj.canvas.getContext("2d");
        ctx.fillStyle = "rgba(98,123,242,.4)";
        ctx.strokeStyle = "rgba(98,123,242,1)";
        ctx.lineWidth = 2;
        ctx.beginPath();
        path.forEach((item) => {
          let pos = map.lngLatToContainer(item);
          ctx.lineTo(pos.x, pos.y);
        });
        ctx.closePath();
        ctx.stroke();
        ctx.fill();
      };

      if (obj.gon) {
        obj.gon.render = onRender;
        map.addLayer(obj.gon);
        obj.gon.show();
      } else {
        obj.gon = new AMap.CustomLayer(obj.canvas, {
          zooms: [0, 20],
          zIndex: 30,
          alwaysRender: true,
        });
        obj.gon.render = onRender; // 将自定义的 render 方法挂在自定义图层的 render 属性上
        map.addLayer(obj.gon);
        obj.gon.show();
      }
    },
    // 获取多边形中心坐标
    getPolygonCenter(lnglatarr) {
      var total = lnglatarr.length;
      var X = 0,
        Y = 0,
        Z = 0;
      lnglatarr.forEach(function (lnglat) {
        var lng = (lnglat[0] * Math.PI) / 180;
        var lat = (lnglat[1] * Math.PI) / 180;
        var x, y, z;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      });
      X = X / total;
      Y = Y / total;
      Z = Z / total;

      var Lng = Math.atan2(Y, X);
      var Hyp = Math.sqrt(X * X + Y * Y);
      var Lat = Math.atan2(Z, Hyp);
      return { lng: (Lng * 180) / Math.PI, lat: (Lat * 180) / Math.PI };
    },
    textClick(e) {
      let data = JSON.parse(e.target.getExtData());
      this.activeGonObj = data;
      this.isDrawGon = true;
      this.isAddMarker = true;
      this.drawGon(this.activeGonObj, true);
    },
    markerDragging(e) {
      let data = JSON.parse(e.target.getExtData());
      let index = this.activeGonObj.pathList.findIndex(
        (item) => item.id == data.id
      );
      this.activeGonObj.pathList[index].lat = e.lnglat.lat;
      this.activeGonObj.pathList[index].lng = e.lnglat.lng;
      this.drawGon(this.activeGonObj, true);
    },
    // 建筑高度设置
    heightInputUploadactiveGonObj() {
      if (this.activeGonObj.height != 0) {
        this.activeGonObj.height = this.activeGonObj.height.replace(
          /^(0+)|[^\d]+/g,
          ""
        );
      }
    },
    tiltInputUploadSector() {
      if (this.sector.tilt != 0) {
        this.sector.tilt = this.sector.tilt.replace(/^(0+)|[^\d]+/g, "");
        if (Number(this.sector.tilt) > 90) {
          this.sector.tilt = 90;
        }
      }
      this.uploadSector();
    },
    inputUploadSector(index) {
      this.sector.areaList[index].radius = this.sector.areaList[
        index
      ].radius.replace(/^(0+)|[^\d]+/g, "");
      this.uploadSector();
    },
    uploadSector() {
      this.drawFan(
        this.detData.longitude,
        this.detData.latitude,
        -90 + Number(this.sector.tilt),
        360 / this.sector.areaNum,
        this.sector.areaList
      );
    },
    // 获取安全设置详情
    getData() {
      let _this = this;
      detAirport(this.$route.params.id).then((res) => {
        console.log("机场详情", res);
        this.detData = res.data;
        _this.zoom = 13;
        this.map.setZoomAndCenter(_this.zoom, [
          _this.detData.longitude,
          _this.detData.latitude,
        ]);
        if (this.detData.sector) {
          this.sector = JSON.parse(this.detData.sector);
          console.log("this.sector", this.sector);
        }
        this.drawFan(
          _this.detData.longitude,
          _this.detData.latitude,
          -90 + Number(_this.sector.tilt),
          360 / _this.sector.areaNum,
          _this.sector.areaList
        );
        this.loadAllGon();
        var icon = new AMap.Icon({
          size: new AMap.Size(30, 30),
          image: require("@/assets/images/hezi.png"),
          imageSize: new AMap.Size(30, 30),
          imageOffset: new AMap.Pixel(0, 0),
        });
        let marker = new AMap.Marker({
          position: [_this.detData.longitude, _this.detData.latitude],
          icon: icon,
          offset: new AMap.Pixel(-15, -15),
          draggable: false,
          zIndex: 9999,
        });
        _this.map.add(marker);
      });
    },
    // 地图扇形安全区域
    drawFan(longitude, latitude, startAngle, includeAngle, radiusList) {
      let _this = this;
      if (!_this.fanCanvas) {
        _this.fanCanvas = document.createElement("canvas");
      }
      let onRender = function () {
        let size = _this.map.getSize();
        _this.fanCanvas.style.width = size.width + "px";
        _this.fanCanvas.style.height = size.height + "px";
        _this.fanCanvas.width = size.width;
        _this.fanCanvas.height = size.height;
        let ctx = _this.fanCanvas.getContext("2d");
        ctx.fillStyle = "rgba(254,111,111,.4)";
        ctx.strokeStyle = "rgba(254,111,111,1)";
        ctx.lineWidth = 1;
        ctx.font = "bold 18px NSimSun";
        let pos = _this.map.lngLatToContainer([longitude, latitude]);
        let Angle = startAngle;

        radiusList.forEach((item) => {
          if (Angle - startAngle >= 360) {
            return;
          }
          ctx.fillStyle = "rgba(254,111,111,.4)";
          ctx.strokeStyle = "rgba(254,111,111,1)";
          var newLngLat = _this.azimuth_offset(
            longitude,
            latitude,
            0,
            item.radius
          ); //距离点的坐标
          let newPos = _this.map.lngLatToContainer(newLngLat);
          let radiusCtx = Math.sqrt(
            (pos.x - newPos.x) * (pos.x - newPos.x) +
              (pos.y - newPos.y) * (pos.y - newPos.y)
          );
          //绘制图形
          ctx.beginPath();
          if (includeAngle == 360) {
            ctx.moveTo(newPos.x, newPos.y);
          } else {
            ctx.moveTo(pos.x, pos.y);
          }
          if (includeAngle == 360) {
            ctx.arc(
              pos.x,
              pos.y,
              radiusCtx,
              (Math.PI * -90) / 180,
              (Math.PI * 360) / 180
            );
          } else {
            ctx.arc(
              pos.x,
              pos.y,
              radiusCtx,
              (Math.PI * Angle) / 180,
              (Math.PI * (Angle + includeAngle)) / 180
            );
          }
          ctx.closePath();
          ctx.stroke();
          ctx.fill();
          ctx.fillStyle = "#000";
          // if(includeAngle == 360) {
          //     let x = pos.x - 10
          //     let y = pos.y + 5
          //     ctx.fillText(item.areaName, x,y)
          // } else {
          //     let x = pos.x + radiusCtx/2 * Math.cos((Angle + includeAngle/2) * Math.PI / 180) - 10
          //     let y = pos.y + radiusCtx/2 * Math.sin((Angle + includeAngle/2) * Math.PI / 180) + 5
          //     ctx.fillText(item.areaName, x,y)
          // }

          if (includeAngle != 360) {
            let x =
              pos.x +
              (radiusCtx / 2) *
                Math.cos(((Angle + includeAngle / 2) * Math.PI) / 180) -
              10;
            let y =
              pos.y +
              (radiusCtx / 2) *
                Math.sin(((Angle + includeAngle / 2) * Math.PI) / 180) +
              5;
            ctx.fillText(item.areaName, x, y);
          }

          Angle += includeAngle;
        });
      };
      if (this.customLayer) {
        this.customLayer.render = onRender;
        _this.map.addLayer(this.customLayer);
      } else {
        this.customLayer = new AMap.CustomLayer(_this.fanCanvas, {
          zooms: [0, 20],
          zIndex: 20,
          alwaysRender: true,
        });
        this.customLayer.render = onRender; // 将自定义的 render 方法挂在自定义图层的 render 属性上
        _this.map.addLayer(this.customLayer);
      }
    },
    /**************************************************************************
     *从指定的原点出发，偏移输入角度后，向此方向延伸输入距离，返回此时的位置
     *origin_lon：原点经度
     *origin_lat：原点纬度
     *azimuth：偏移角度
     *distance：延伸距离
     *ret_lon:返回位置的经度
     *ret_lat:返回位置的纬度
     **************************************************************************/
    azimuth_offset(origin_lon, origin_lat, azimuth, distance) {
      var lonlat = [0.0, 0.0];
      if (azimuth != null && distance > 0) {
        lonlat[0] =
          origin_lon +
          (distance * Math.sin((azimuth * Math.PI) / 180) * 180) /
            (Math.PI * 6371229 * Math.cos((origin_lat * Math.PI) / 180));
        lonlat[1] =
          origin_lat +
          (distance * Math.cos((azimuth * Math.PI) / 180)) /
            ((Math.PI * 6371229) / 180);
      } else {
        lonlat[0] = origin_lon;
        lonlat[1] = origin_lat;
      }
      return lonlat;
    },
    initMap() {
      let _this = this;
      window._AMapSecurityConfig = {
        securityJsCode: amapSecretkey,
      };
      AMapLoader.load({
        key: amapKey,
        version: "2.0",
        plugins: [
          // "AMap.Geocoder",
          "AMap.PlaceSearch",
        ],
      })
        .then((AMap) => {
          _this.map = new AMap.Map("security-map", {
            zoom: _this.zoom,
            mapStyle: "amap://styles/whitesmoke",
            WebGLParams: { preserveDrawingBuffer: true },
          });
          // _this.geocoder = new AMap.Geocoder({
          //     radius: 1000 //范围，默认：500
          // });
          _this.placeSearch = new AMap.PlaceSearch({ city: "全国" });
          _this.getData();
          _this.map.on("click", this.mapClick);
        })
        .catch((e) => {
          // console.log(e);
        });
    },
    // 地图点击事件
    mapClick(e) {
      // console.log("地图点击事件",e)
      if (this.isDrawGon) {
        if (!this.isAddMarker) {
          let strnum = createUniqueString();
          this.activeGonObj = {
            area: 0,
            color: "#627bf2",
            id: strnum,
            pathList: [],
            lat: e.lnglat.lat,
            lng: e.lnglat.lng,
            height: 5000,
          };
          this.isAddMarker = true;
        }
        let obj = {
          lng: e.lnglat.lng,
          lat: e.lnglat.lat,
          id: createUniqueString(),
          gonId: this.activeGonObj.id,
        };
        this.activeGonObj.pathList.push(obj);
        this.drawGon(this.activeGonObj, true);
      } else {
        let gonIndex = -1;
        this.sector.constructAreaList.forEach((item, index) => {
          let path = item.pathList.map((item) => {
            return [item.lng, item.lat];
          });
          let isPointInRing = AMap.GeometryUtil.isPointInRing(e.lnglat, path);
          if (isPointInRing) {
            gonIndex = index;
          }
        });
        // console.log("gonIndex",gonIndex)
        if (gonIndex !== -1) {
          this.activeGonObj = JSON.parse(
            JSON.stringify(this.sector.constructAreaList[gonIndex])
          );
          this.isDrawGon = true;
          this.isAddMarker = true;
          this.drawGon(this.activeGonObj, true);
        }
      }
      // let isok = this.isFan(e.pixel)
      // console.log(isok)
    },
    // 判断是否点击在安全区域,lnglat 点击经纬度，pixel点击像素位置
    isFan(pixel) {
      let _this = this;
      // 中心点像素位置
      let pos = _this.map.lngLatToContainer([
        _this.detData.longitude,
        _this.detData.latitude,
      ]);
      //点击点和中心点的像素距离
      let radius = Math.sqrt(
        (pos.x - pixel.x) * (pos.x - pixel.x) +
          (pos.y - pixel.y) * (pos.y - pixel.y)
      );
      //对边 sin
      let sin = (pixel.y - pos.y) / radius;
      let angle = Math.round((Math.asin(sin) * 180) / Math.PI);
      if (this.sector.areaNum == 1) {
        var newLngLat = _this.azimuth_offset(
          _this.detData.longitude,
          _this.detData.latitude,
          0,
          _this.sector.areaList[0].radius
        ); //距离点的坐标
        let newPos = _this.map.lngLatToContainer(newLngLat);
        let radiusCtx = Math.sqrt(
          (pos.x - newPos.x) * (pos.x - newPos.x) +
            (pos.y - newPos.y) * (pos.y - newPos.y)
        );
        if (radiusCtx > radius) {
          return true;
        } else {
          return false;
        }
      } else {
        let area = _this.ofArea(pos, pixel); //属于哪个区域，1下右，2下左，3上左，4上右
        let startAngle = _this.sector.tilt - 90;
        let includeAngle = 360 / _this.sector.areaNum;
        if (area == 1) {
          angle = angle;
        } else if (area == 2) {
          angle = 90 - angle + 90;
        } else if (area == 3) {
          angle = 180 - angle;
        } else {
          angle = 270 + (90 + angle);
        }
        let isok = false;
        for (let i = 0; i < _this.sector.areaNum; i++) {
          if (startAngle < 0) {
            let start = 360 + startAngle;
            let end = start + includeAngle;
            if (end > 360) {
              if (
                (angle > start && angle < 360) ||
                (angle > 0 && angle < end - 360)
              ) {
                var newLngLat = _this.azimuth_offset(
                  _this.detData.longitude,
                  _this.detData.latitude,
                  0,
                  _this.sector.areaList[i].radius
                ); //距离点的坐标
                let newPos = _this.map.lngLatToContainer(newLngLat);
                let radiusCtx = Math.sqrt(
                  (pos.x - newPos.x) * (pos.x - newPos.x) +
                    (pos.y - newPos.y) * (pos.y - newPos.y)
                );
                if (radiusCtx > radius) {
                  isok = true;
                }
              }
            } else {
              if (angle > start && angle < end) {
                var newLngLat = _this.azimuth_offset(
                  _this.detData.longitude,
                  _this.detData.latitude,
                  0,
                  _this.sector.areaList[i].radius
                ); //距离点的坐标
                let newPos = _this.map.lngLatToContainer(newLngLat);
                let radiusCtx = Math.sqrt(
                  (pos.x - newPos.x) * (pos.x - newPos.x) +
                    (pos.y - newPos.y) * (pos.y - newPos.y)
                );
                if (radiusCtx > radius) {
                  isok = true;
                }
              }
            }
            startAngle += includeAngle;
          } else {
            let start = startAngle;
            let end = start + includeAngle;
            if (end > 360) {
              if (
                (angle > start && angle < 360) ||
                (angle > 0 && angle < end - 360)
              ) {
                var newLngLat = _this.azimuth_offset(
                  _this.detData.longitude,
                  _this.detData.latitude,
                  0,
                  _this.sector.areaList[i].radius
                ); //距离点的坐标
                let newPos = _this.map.lngLatToContainer(newLngLat);
                let radiusCtx = Math.sqrt(
                  (pos.x - newPos.x) * (pos.x - newPos.x) +
                    (pos.y - newPos.y) * (pos.y - newPos.y)
                );
                if (radiusCtx > radius) {
                  isok = true;
                }
              }
            } else {
              if (angle > start && angle < end) {
                var newLngLat = _this.azimuth_offset(
                  _this.detData.longitude,
                  _this.detData.latitude,
                  0,
                  _this.sector.areaList[i].radius
                ); //距离点的坐标
                let newPos = _this.map.lngLatToContainer(newLngLat);
                let radiusCtx = Math.sqrt(
                  (pos.x - newPos.x) * (pos.x - newPos.x) +
                    (pos.y - newPos.y) * (pos.y - newPos.y)
                );
                if (radiusCtx > radius) {
                  isok = true;
                }
              }
            }
            startAngle += includeAngle;
          }
        }
        return isok;
      }
    },
    ofArea(pos, pixel) {
      if (pixel.x - pos.x > 0) {
        if (pixel.y - pos.y > 0) {
          return 1;
        } else {
          return 4;
        }
      } else {
        if (pixel.y - pos.y > 0) {
          return 2;
        } else {
          return 3;
        }
      }
    },
    // 控制搜索空是否显示
    ShowAddressSearch() {
      if (this.isShowAddressSearch) {
        this.isShowAddressSearch = false;
        this.addressSearch = "";
        this.addressOptions = [];
        if (this.addressMarker) {
          this.addressMarker.remove();
          this.addressMarker = null;
        }
      } else {
        this.isShowAddressSearch = true;
      }
    },
    // 地址选择
    addressSelect(val) {
      // console.log(val)
      let index = this.addressOptions.findIndex((item) => item.id == val);
      this.zoom = 12;
      this.map.setZoomAndCenter(this.zoom, [
        this.addressOptions[index].location.lng,
        this.addressOptions[index].location.lat,
      ]);
      if (this.addressMarker) {
        this.addressMarker.remove();
        this.addressMarker = null;
      }
      const icon = new AMap.Icon({
        size: new AMap.Size(24, 24),
        image: require("@/assets/images/mapicon/a16.png"),
        imageSize: new AMap.Size(24, 24),
        imageOffset: new AMap.Pixel(0, 0),
      });
      this.addressMarker = new AMap.Marker({
        position: [
          this.addressOptions[index].location.lng,
          this.addressOptions[index].location.lat,
        ],
        icon: icon,
        offset: new AMap.Pixel(-12, -12),
      });
      this.map.add(this.addressMarker);
    },
    // 地址搜索
    remoteMethod(val) {
      let _this = this;
      if (val !== "") {
        this.addressSearchLoading = true;
        this.placeSearch.search(val, (status, result) => {
          if (status == "complete" && result.poiList) {
            _this.addressSearchLoading = false;
            _this.addressOptions = result.poiList.pois;
          }
        });
      } else {
        this.addressOptions = [];
      }
    },
    //切换地图图层
    switchLayer() {
      if (!this.satellite) {
        this.satellite = new AMap.TileLayer.Satellite(); //卫星图层
      }
      if (this.isaddLayer) {
        this.isaddLayer = false;
        this.map.removeLayer(this.satellite);
      } else {
        this.isaddLayer = true;
        this.map.addLayer(this.satellite);
      }
    },
    // 放大图层
    addZoom() {
      if (this.zoom < 20) {
        this.zoom = this.zoom + 2;
        this.map.setZoom(this.zoom);
      } else {
        this.$modal.msgWarning("不能再放大了");
      }
    },
    // 缩小图层
    reduceZoom() {
      if (this.zoom > 6) {
        this.zoom = this.zoom - 2;
        this.map.setZoom(this.zoom);
      } else {
        this.$modal.msgWarning("不能再缩小了");
      }
    },
  },
  mounted() {
    this.initMap();
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #f5f5f5;
  position: relative;
}
.w-map {
  width: 100%;
  height: 100%;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid rgba(73, 68, 78, 0.2);
}
.w-right-tool {
  position: absolute;
  width: 45px;
  right: 360px;
  bottom: 40px;
  display: flex;
  flex-direction: column;
  img {
    width: 45px;
    height: 45px;
    margin-top: 10px;
    cursor: pointer;
  }
}
.w-right-search {
  position: absolute;
  width: 260px;
  height: 40px;
  right: 420px;
  bottom: 207px;
  // background: #fff;
}
.w-right {
  position: absolute;
  width: 300px;
  height: calc(100% - 80px);
  top: 40px;
  right: 40px;
  background: url("../../../assets/images/plan_bg.png");
  background-size: 100% 100%;
  opacity: 0.9;
  border-radius: 10px;
  padding: 20px;
  .w-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 55px;
    padding-bottom: 15px;
    border-bottom: 1px solid rgb(82, 78, 82);
    div {
      display: flex;
      align-items: center;
      color: #fff;
      font-size: 14px;
      font-weight: 600;
      i {
        font-size: 20px;
        cursor: pointer;
      }
      span {
        margin-left: 5px;
      }
      img {
        cursor: pointer;
      }
    }
  }
  .w-right-box {
    width: 100%;
    height: calc(100% - 120px);
    overflow: auto;
    .w-box-title {
      color: #fff;
      font-size: 14px;
      font-weight: 600;
      margin: 20px 0;
    }
    .w-area {
      display: flex;
      width: 100%;
      justify-content: space-between;
      flex-wrap: wrap;
      .w-cell1 {
        width: 50%;
        height: 40px;
        display: flex;
        align-items: center;
        margin-top: 10px;
        span {
          font-size: 14px;
          color: #fff;
          font-weight: 600;
          width: 30px;
          text-align: center;
        }
        input {
          height: 34px;
          margin: auto;
          width: calc(100% - 40px);
          border: none;
          color: rgb(255, 255, 255);
          font-size: 14px;
          border-radius: 5px;
          overflow: hidden;
          background: rgba(255, 255, 255, 0.1);
          text-indent: 20px;
          outline: none;
        }
      }
    }
    .w-cell {
      width: 100%;
      min-height: 40px;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      margin-top: 10px;
      span {
        font-size: 14px;
        color: #fff;
        font-weight: 600;
        width: 60px;
      }
      p {
        width: calc(100% - 80px);
        margin: auto;
        font-size: 14px;
        text-indent: 20px;
        color: #fff;
        font-weight: 700;
      }
      input {
        height: 34px;
        margin: auto;
        width: calc(100% - 80px);
        border: none;
        color: rgb(255, 255, 255);
        font-size: 14px;
        border-radius: 5px;
        overflow: hidden;
        background: rgba(255, 255, 255, 0.1);
        text-indent: 20px;
        outline: none;
      }
      .input1 {
        cursor: not-allowed;
      }

      .w-select {
        width: calc(100% - 80px);
        height: 34px;
        margin: auto;
        // display: flex;
        // align-items: center;
        // justify-content: space-between;
        // color: rgb(255, 255, 255);
        // border-radius: 5px;
        // background: rgba(255, 255, 255, 0.1);
        // padding: 0 10px 0 15px;
        // cursor: pointer;
        .w-xian {
          width: 100px;
          height: 2px;
          border-top: 2px dashed #fff;
        }
        .w-xian1 {
          width: 100px;
          height: 2px;
          border-top: 2px solid #fff;
        }
        .w-xian2 {
          width: 100px;
          height: 2px;
          border-top: 2px dashed #fff;
        }
        .w-xian3 {
          width: 100px;
        }
        .w-se-box {
          width: 24px;
          height: 24px;
        }
      }
      .w-option-img {
        background: rgba(0, 0, 0, 0.5);
        width: calc(100% - 80px);
        height: auto;
        margin-left: 60px;
        margin-top: 5px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        img {
          padding: 3px;
          margin: 5px;
          cursor: pointer;
          &:hover {
            background: rgba(255, 255, 255, 0.1);
          }
        }
        & > div {
          &:hover {
            background: rgba(255, 255, 255, 0.1);
          }
          width: 100%;
          height: 32px;
          line-height: 32px;
          cursor: pointer;
          .w-xian1 {
            width: 100px;
            height: 2px;
            border-top: 2px solid #fff;
            margin: 15px 10px;
          }
          .w-xian2 {
            width: 100px;
            height: 2px;
            border-top: 2px dashed #fff;
            margin: 15px 10px;
          }
          .w-xian3 {
            width: 100px;
            margin: 10px 10px;
          }
        }
      }
      .w-option-box {
        background: rgba(0, 0, 0, 0.5);
        width: calc(100% - 80px);
        height: auto;
        margin-left: 60px;
        margin-top: 5px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        div {
          width: 24px;
          height: 24px;
          margin: 8px;
          cursor: pointer;
        }
      }
    }
  }
  .w-btn {
    width: 100%;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid rgb(82, 78, 82);
    div {
      width: 120px;
      height: 35px;
      border-radius: 5px;
      line-height: 35px;
      text-align: center;
      cursor: pointer;
      background: rgba(0, 0, 0, 0.5);
      color: rgb(255, 255, 255);
      font-size: 15px;
      letter-spacing: 2px;
      font-weight: 700;
    }
  }
}

.w-delete-btn {
  width: 80%;
  height: 35px;
  margin: 0 auto;
  text-align: center;
  border-radius: 5px;
  line-height: 35px;
  color: #fff;
  background: rgba(228, 66, 66, 0.5);
  margin-top: 20px;
  cursor: pointer;
}

::v-deep {
  .w-select {
    .el-input__inner {
      background: rgba(255, 255, 255, 0.1);
      border: none;
      color: rgb(255, 255, 255);
    }
  }
}
</style>
